import React from 'react';
import {ScrollView, Text, View} from 'react-native';
import {getRealSize, Touchable} from '../../utils';
import ThemeStyles from '../../styles';
import Validator from 'async-validator';
import Toast from '../../components/toast';
import InputItem from '../../components/input-item';
import Button from '../../components/button';
import {bindActionCreators} from 'redux';
import * as forgetActionCreator from '../../actions/forget-actions';
import {connect} from 'react-redux';
import {I18n} from '../../reducers/intl';

class ForgetPwdScreen extends React.PureComponent {
  static navigationOptions = ({navigation}) => ({
    title: I18n.t('page.title.forget'),
    headerLeft: () => (
      <Touchable onPress={() => navigation.popToTop()}>
        <View style={[ThemeStyles.Layout.base.padding]}>
          <Text style={[ThemeStyles.Front.base]}>
            {I18n.t('button.cancel')}
          </Text>
        </View>
      </Touchable>
    ),
  });

  constructor() {
    super();
    this.state = {
      timerCount: 0,
      timer: null,
    };
    this.emailValidator = new Validator({
      email: [
        {
          required: true,
          message: I18n.t('form.validate.message.email'),
        },
        {type: 'email', message: I18n.t('form.validate.message.format')},
      ],
    });
    this.validator = new Validator({
      email: [
        {
          required: true,
          message: I18n.t('form.validate.message.email'),
        },
        {type: 'email', message: I18n.t('form.validate.message.format')},
      ],
      captcha: [
        {
          required: true,
          message: I18n.t('form.validate.message.code'),
        },
        {
          len: 6,
          message: I18n.t('form.validate.message.codeLength'),
        },
        {
          validator: (rule, value, callback, source) => {
            if (source.code === value) {
              return callback();
            }
            callback(new Error(I18n.t('form.validate.message.codeDiff')));
          },
        },
      ],
      password: [
        {
          required: true,
          message: I18n.t('form.validate.message.password'),
        },
      ],
      confirmPassword: [
        {
          required: true,
          message: I18n.t('form.validate.message.confirmPassword'),
        },
        {
          validator: (rule, value, callback, source) => {
            if (source.password === value) {
              return callback();
            }
            callback(new Error(I18n.t('form.validate.message.passwordDiff')));
          },
        },
      ],
    });
  }

  componentWillUnmount() {
    if (this.state.timer) {
      clearInterval(this.state.timer);
      this.setState({timer: null, timerCount: 0});
    }
  }

  onChangeValue = async (value, field) => {
    const {form, forgetActions} = this.props;
    forgetActions.update({[field]: value});
    const dataForm = {
      ...form,
      [field]: value,
    };
    try {
      await this.validator.validate(dataForm);
      this.setState({
        allowSubmit: true,
        errors: [],
      });
    } catch (errors) {
      this.setState({
        allowSubmit: false,
        errors,
      });
    }
  };

  onGetCode = async () => {
    const {form, forgetActions} = this.props;
    try {
      await this.emailValidator.validate({email: form.email});
      this.startTimer();
      await forgetActions.sendCaptcha(form.email);
      Toast.show(I18n.t('form.validate.message.codeSend'));
    } catch (e) {
      if (e.message === 'Request failed with status code 406') {
        Toast.show(I18n.t('form.validate.message.userExists'));
      } else if (e.errors) {
        Toast.show(e.errors[0].message);
      } else {
        Toast.show(e.message);
      }
      this.clearTimer();
    }
  };

  startTimer = () => {
    this.clearTimer();
    this.setState(
      {
        timerCount: 60,
      },
      () => {
        const timer = setInterval(() => {
          if (this.state.timerCount > 0) {
            this.setState({timerCount: this.state.timerCount - 1});
          } else {
            this.clearTimer();
          }
        }, 1000);
        this.setState({
          timer,
        });
      },
    );
  };

  clearTimer = () => {
    if (this.state.timer) {
      clearInterval(this.state.timer);
      this.setState({
        timerCount: 0,
        timer: null,
      });
    }
  };

  onSubmit = async () => {
    const {form, navigation, forgetActions} = this.props;
    try {
      await this.validator.validate(form);
      forgetActions.submit(form);
      navigation.goBack();
    } catch (e) {
      Toast.show(e.errors[0].message);
    }
  };

  render() {
    const {form} = this.props;
    return (
      <ScrollView
        style={[ThemeStyles.Layout.flex['1'], ThemeStyles.Layout.base.padding]}>
        {form.code && <Text>{form.code}</Text>}
        <View style={[ThemeStyles.Layout.base.mt]}>
          <InputItem
            placeholder={I18n.t('form.validate.message.email')}
            isRequire
            value={form.email}
            maxLength={22}
            keyboardType="email-address"
            onChange={value => this.onChangeValue(value, 'email')}
          />
        </View>
        <View
          style={[
            ThemeStyles.Layout.flex.row,
            ThemeStyles.Layout.flex.between,
            ThemeStyles.Layout.base.mt,
            ThemeStyles.Layout.flex.center,
          ]}>
          <View style={{flex: 2}}>
            <InputItem
              placeholder={I18n.t('form.placeholder.code')}
              isRequire
              value={form.captcha}
              maxLength={6}
              keyboardType="numeric"
              onChange={value => this.onChangeValue(value, 'captcha')}
            />
          </View>
          <View style={{flex: 1, marginLeft: getRealSize(15)}}>
            <Button
              size="middle"
              onPress={this.onGetCode}
              type="ghost"
              width={98}
              disabled={!!this.state.timerCount}
              label={
                this.state.timerCount
                  ? I18n.t('button.resend', {count: this.state.timerCount})
                  : I18n.t('button.code')
              }
            />
          </View>
        </View>
        <View style={[ThemeStyles.Layout.base.mt]}>
          <InputItem
            placeholder={I18n.t('form.placeholder.password')}
            secureTextEntry
            isRequire
            maxLength={22}
            value={form.password}
            onChange={value => this.onChangeValue(value, 'password')}
          />
        </View>
        <View style={[ThemeStyles.Layout.base.mt]}>
          <InputItem
            placeholder={I18n.t('form.placeholder.confirmPassword')}
            secureTextEntry
            isRequire
            maxLength={22}
            value={form.confirmPassword}
            onChange={value => this.onChangeValue(value, 'confirmPassword')}
          />
        </View>
        <View style={[ThemeStyles.Layout.base.mt]}>
          <Button label={I18n.t('button.reset')} onPress={this.onSubmit} />
        </View>
      </ScrollView>
    );
  }
}

const mapStateToProps = state => ({
  appState: state.appState,
  device: state.device,
  user: state.user,
  token: state.token,
  form: state.forgetForm,
});

const mapDispatchToProps = dispatch => ({
  forgetActions: bindActionCreators(forgetActionCreator, dispatch),
});

export default connect(mapStateToProps, mapDispatchToProps)(ForgetPwdScreen);
